package com.danger.Activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.ListView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by 俊 on 2016/6/4.
 */
public class ImageLoader {

    private static final int GET_BITMAP_BY_THREAD = 1;
    private ImageView imageView;
    private String url;
    //创建cache（最近最少使用算法Least Recently Used）
    private LruCache<String, Bitmap> lruCache;
    private ListView listView;
    private Set<ImageAsyncTask> tasks;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_BITMAP_BY_THREAD:
                    if (imageView.getTag().equals(url))
                        imageView.setImageBitmap((Bitmap) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    public ImageLoader(ListView listView) {
        this.listView = listView;
        tasks = new HashSet<>();
        //获取最大可用内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        //取最大可用内存的1/4作为缓存空间
        int cacheSize = maxMemory / 4;
        lruCache = new LruCache<String, Bitmap>(cacheSize) {
            /**
             * 该方法必须重写，不重写的话返回的是bitmap的个数，重写之后返回每次放入的bitmap的size
             * 在每次写入的时候调用
             * @param key
             * @param value
             * @return
             */
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };
    }

    /**
     * 用于加载从start到end之间的图片
     *
     * @param start
     * @param end
     */
    public void loadImages(int start, int end) {
        for (int i = start; i < end; i++) {
            String url = NewsAdapter.urls[i];
            Bitmap bitmap = getBitmapFromCache(url);
            if (bitmap == null) {
                ImageAsyncTask task = new ImageAsyncTask(url);
                task.execute(url);
                tasks.add(task);
            } else {
                ImageView imageView = (ImageView) listView.findViewWithTag(url);
                imageView.setImageBitmap(bitmap);
            }
        }
    }

    public void cancelAllTask() {
        if (tasks != null) {
            for (ImageAsyncTask task : tasks) {
                task.cancel(false);
            }
        }
    }

    /**
     * 利用Thread方式加载网络图片
     *
     * @param imageView
     * @param url
     */
    public void loadImageByThread(ImageView imageView, final String url) {

        this.imageView = imageView;
        this.url = url;

        new Thread() {

            @Override
            public void run() {
                super.run();
                Bitmap bitmap = getBitmap(url);
                Message message = Message.obtain();
                message.obj = bitmap;
                message.what = GET_BITMAP_BY_THREAD;
                handler.sendMessage(message);
            }
        }.start();
    }

    /**
     * 利用AsyncTask方式加载网络图片
     *
     * @param imageView
     * @param url
     */
    public void loadImageByAsyncTask(ImageView imageView, String url) {
        Bitmap bitmap = getBitmapFromCache(url);
        if (bitmap == null) {
            imageView.setImageResource(R.mipmap.ic_launcher);
        } else {
            imageView.setImageBitmap(bitmap);
        }
    }

    public Bitmap getBitmap(String urlString) {
        Bitmap bitmap;
        InputStream inputStream = null;
        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            inputStream = new BufferedInputStream(urlConnection.getInputStream());
            bitmap = BitmapFactory.decodeStream(inputStream);
            urlConnection.disconnect();
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

        //        private ImageView mImageView;
        private String mUrl;

        public ImageAsyncTask(String url) {
//            mImageView = imageView;
            mUrl = url;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = getBitmap(params[0]);
            if (bitmap != null)
                addBitmapToCache(params[0], bitmap);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            ImageView imageView = (ImageView) listView.findViewWithTag(mUrl);
            if (imageView != null && bitmap != null) {
                imageView.setImageBitmap(bitmap);
            }
            tasks.remove(this);
        }
    }

    /**
     * 将图片加载进缓存
     *
     * @param url
     * @param bitmap
     */
    public void addBitmapToCache(String url, Bitmap bitmap) {
        if (lruCache.get(url) == null) {
            lruCache.put(url, bitmap);
        }
    }

    /**
     * 在缓存中获取缓存的图片
     *
     * @param url
     * @return
     */
    public Bitmap getBitmapFromCache(String url) {
        return lruCache.get(url);
    }
}
